package com.itouch.bracelet.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.Child;
import com.itouch.bracelet.bean.ChildRegisterResult;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bean.UploadResult;
import com.itouch.bracelet.bluetooth.BluetoothConstants;
import com.itouch.bracelet.bluetooth.BluetoothPacket;
import com.itouch.bracelet.bluetooth.BluetoothSpp;
import com.itouch.bracelet.bluetooth.BluetoothUtil;
import com.itouch.bracelet.bluetooth.BluetoothValue;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.CoFileUtil;
import com.itouch.util.CommonMethodTools;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.widget.ActionSheet;
import com.itouch.widget.ActionSheet.ActionSheetListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
/**
 * 孩子信息更改，包括更改头像and so on
 * @author SunshineHu
 * @date Fool's Day 2015
 * Happy Fool's Day 
 */
public class ChildEditActivity extends BaseActivity implements
		OnClickListener, OnDateSetListener,ActionSheetListener {
	public static final String DATEPICKER_TAG = "datepicker";
	private EditText childName;
	private EditText childDate;
	private EditText deviceCode;
	private TextView deviceCodeGet;
	private TextView commit_register;
	private ImageView logo;
	private RadioGroup sex;
	private RadioButton male;
	private RadioButton female;
	private static final int requestQRCode = 0x2234;
	private ImageView calendarView;
	private DatePickerDialog startDatePickerDialog;

	private DisplayImageOptions options;
	
	private Uri uri=null;
	private Child child;
	
	
	@Override
	protected int setContentViewById() {
		return R.layout.activity_child_edit;
	}

	@Override
	protected void initViews() {
		
		options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.c_default_avatar)
		.showImageOnFail(R.drawable.c_default_avatar)
		.resetViewBeforeLoading(true).cacheOnDisc(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300)).build();
		
		final Calendar calendar = Calendar.getInstance();
		startDatePickerDialog = DatePickerDialog.newInstance(this,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), false);

		childName = (EditText) findViewById(R.id.child_name);
		childDate = (EditText) findViewById(R.id.child_date);
		deviceCode = (EditText) findViewById(R.id.device_code);
		deviceCodeGet = (TextView) findViewById(R.id.device_code_get);
		commit_register = (TextView) findViewById(R.id.commit_register);
		calendarView = (ImageView) findViewById(R.id.calendar);
		logo=(ImageView) findViewById(R.id.logo);
		
		deviceCodeGet.setOnClickListener(this);
		calendarView.setOnClickListener(this);
		commit_register.setOnClickListener(this);
		logo.setOnClickListener(this);
		sex = (RadioGroup) findViewById(R.id.sex);
		male = (RadioButton) findViewById(R.id.male);
		female = (RadioButton) findViewById(R.id.female);

	}

	@Override
	protected void initData() {

		LoginUser user=UserCache.getOauth(this);//获取孩子信息
		child=user.getChildlist().get(user.childPosition);
		
		ImageLoader.getInstance().displayImage(child.getPath(), logo, options);
		childName.setText(child.getName());

		if(!child.getBornTime().equals("")){
			if(child.getBornTime().contains(" ")){
				String date=child.getBornTime().substring(0, child.getBornTime().indexOf(" "));
				childDate.setText(date);
			}else{
				childDate.setText(child.getBornTime());
			}
		}
		deviceCode.setText(child.getDeviceNo());
		
		String sex=child.getSex();
		if(sex.equals("1")){
			male.setChecked(true);
		}else{
			female.setChecked(true);
		}
		
	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {
		case R.id.calendar:
			startDatePickerDialog.setVibrate(true);
			startDatePickerDialog.setYearRange(1985, 2028);
			startDatePickerDialog.setCloseOnSingleTapDay(true);
			startDatePickerDialog.show(getSupportFragmentManager(),
					DATEPICKER_TAG);

			break;
		case R.id.device_code_get:
			// 获取设备号
			it = new Intent(context, QrCodeActivity.class);
			startActivityForResult(it, requestQRCode);

			break;
		case R.id.commit_register:
			String nameString = childName.getText().toString();
			if (nameString == null || nameString.length() < 1) {
				Toast.makeText(context, R.string.register_child_name,
						Toast.LENGTH_LONG).show();
				return;
			}

			if (!male.isChecked() && !female.isChecked()) {
				Toast.makeText(context, R.string.register_child_sex,
						Toast.LENGTH_LONG).show();
				return;
			}

			String dateString = childDate.getText().toString();
			if (dateString == null || dateString.length() < 1) {
				Toast.makeText(context, R.string.register_child_date,
						Toast.LENGTH_LONG).show();
				return;
			}

			String deviceString = deviceCode.getText().toString().trim();
			
			if(!deviceString.equals("")){
			
				if (BluetoothUtil.getDeviceType(deviceString)==0) {
					Toast.makeText(context, R.string.register_device,
							Toast.LENGTH_LONG).show();
					return;
				}
				
	//			childRegister(dateString, deviceString, nameString, sex);
				
				if(!child.getDeviceNo().equals(deviceString)){
					if(BluetoothValue.INSTANCE.getConnectStatus()!=BluetoothConstants.STATUS_CONNECTED){
						Toast.makeText(this, "连接手环后才能修改设备号！", Toast.LENGTH_SHORT)
						.show();
						return;
					}
				}
			
			}
			
			String sex = male.isChecked() ? "1" : "0"; // 1:男， 2：女
			
			new ChildRegisterAsync(dateString, deviceString, nameString, sex).execute();

			
			
			
			break;
		case R.id.logo:
			//修改头像
			setTheme(R.style.ActionSheetStyleIOS7);
			ActionSheet.createBuilder(this, getSupportFragmentManager())
			.setCancelButtonTitle("取消")
			.setOtherButtonTitles("拍照", "从相册选择")
			.setCancelableOnTouchOutside(true).setListener(this).show();
			break;
		default:
			break;

		}

	}

	
	/**
	 * 
	 * 小孩注册的AsyncTask
	 */
	class ChildRegisterAsync extends AsyncTask<String, String, String> {

		String bornTime; String childDeviceNum;
		String name;String sex;

		public ChildRegisterAsync(String bornTime, String childDeviceNum,
				String name, String sex) {
			super();
			this.bornTime = bornTime;
			this.childDeviceNum = childDeviceNum;
			this.name = name;
			this.sex = sex;
		}

		

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			show();
		}

		@Override
		protected String doInBackground(String... params) {
			String ss = null;
			try {
				List<NameValuePair> lists = new ArrayList<NameValuePair>();

				lists.add(new BasicNameValuePair("id", child.getId()));
				lists.add(new BasicNameValuePair("bornTime", bornTime));
				lists.add(new BasicNameValuePair("childDeviceNum", childDeviceNum + ""));
				lists.add(new BasicNameValuePair("sex", sex + ""));
				lists.add(new BasicNameValuePair("name", name + ""));

				ss = JsonAndPhpUtil.postHttpData(Constants.CHILD_EDIT, lists, context);
			} catch (Exception e) {

			}
			return ss;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			disMiss();
			if (result == null || "".equals(result)) {
				return;
			}
			Log.d("CHILD_REGISTER",
					"CHILD_REGISTER" + result.toString());
			try {
				ChildRegisterResult a = new Gson().fromJson(
						result.toString(), ChildRegisterResult.class);
				if (a == null) {
					return;
				}
				if (a.isFlag()) {
					/*Toast.makeText(context, R.string.child_register_ok,
							Toast.LENGTH_LONG).show();
					//注册成功后将小孩的信息缓存	
					LoginUser user = UserCache.getOauth(context);
					ArrayList<Child> list = user.getChildlist();
					if (list == null) {
						list = new ArrayList<Child>();
					}
					list.add(a.getRows());
					UserCache.saveOAuth(user, context);
					ChildEditActivity.this.finish();*/
					
					Toast.makeText(context, "修改成功！",
							Toast.LENGTH_LONG).show();
					LoginUser user=UserCache.getOauth(ChildEditActivity.this);
					Child child = user.getChildlist().get(user.childPosition);
					
					child.setBornTime(bornTime);
					child.setDeviceNo(childDeviceNum);
					child.setName(name);
					child.setSex(sex);
					
					child.setCustomerFlag(BluetoothUtil.getDeviceType(deviceCode.getText().toString()));
					
					UserCache.saveOAuth(user, ChildEditActivity.this);
					
					
					////同步到硬件上去
					/*String[] device=deviceString.split(":");
					int part1=Integer.valueOf(device[0]);
					int part2=Integer.valueOf(device[1]);
					*/
					
					sendPacket();
					
					
					finish();
					
				} else {
					Toast.makeText(context, a.getMsg() + "",
							Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
			}

		}
	}
	
	

	@Override
	public void onDateSet(DatePickerDialog datePickerDialog, int year,
			int month, int day) {
		if (year == 0) {
			childDate.setText("");
			return;
		}
		Date d = new Date();
		d.setYear(year - 1900);
		d.setMonth(month);
		d.setDate(day);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(d);
		childDate.setText(date);

	}

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		// TODO Auto-generated method stub
		// 检测是否有sd卡
		if (!CoFileUtil.haveSDCard()) {
			return;
		}
		// sd卡剩余容量大于5M
		if (CoFileUtil.getSDFreeSize() < 5) {
			return;
		}
		
		// 自定义的uri 创建，用于保存保存拍照后的图片，（存在sd卡）
		try {

			String cacheDir = Environment.getExternalStorageDirectory()+"/xiaoai/temp";
			
			File dir = new File(cacheDir);
			if (!dir.exists()) {
				dir.mkdirs(); // 创建文件夹
			}
			String fileName = cacheDir + "/"
					+ "temp.jpg";
			File file = new File(fileName);
			file.delete();
			if (!file.exists()) {
				file.createNewFile();// 创建文件
			}
			uri = Uri.fromFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (index == 0) {
			// 调用相机
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			startActivityForResult(intent, 123);
		} else if (index == 1) {
			// 相册的选择
			Intent picture = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(picture, 456);

		}
	}
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if(resultCode!=RESULT_OK){
			return;
		}
		if (requestCode == 789) {
			// 裁剪的回调
			//上传图片
			
			File tempFile=new File(Environment.getExternalStorageDirectory()+"/xiaoai/temp/temp.jpg");
			if(tempFile.exists()){
				new uploadImage().execute(tempFile);
			}
			
		}
		if (requestCode == 123) {
			// 开始拍照的裁剪 （uri为自定义）
			startPhotoZoom(uri);
		}
		if (requestCode == 456 && intent != null) {
			// 根据系统相册返回的uri 进行图片裁剪
			startPhotoZoom(intent.getData());
		}
		
		if(requestCode==requestQRCode){
			
			deviceCode.setText(intent.getStringExtra("code"));
			
		}
	}

	public void startPhotoZoom(Uri uri1) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri1, "image/*");
		intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
		intent.putExtra("aspectX", 1);// 这两项为裁剪框的比例.
		intent.putExtra("aspectY", 1);// 
		intent.putExtra("output", uri);
		intent.putExtra("outputFormat", "JPEG");// 返回格式
		startActivityForResult(intent, 789);
	}

	
	class uploadImage extends AsyncTask<File, Object, UploadResult>{

		@Override
		protected UploadResult doInBackground(File... params) {
			// TODO Auto-generated method stub
			String ss=CommonMethodTools.uploadFile(params[0], Constants.URL+"/mobi/friendCircle/singleUploadAttachment");
			UploadResult result=new Gson().fromJson(ss, UploadResult.class);
			return result;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			show();
		}

		@Override
		protected void onPostExecute(final UploadResult result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result!=null){
				Map<String, String> params=new HashMap<String, String>();
				params.put("path", result.getPath());
				params.put("objId", child.getId());
				getJSONByVolleyPOST(Constants.URL+"/mobi/customer/insertAttachment", params, new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						try {
							BaseResult a = new Gson().fromJson(
									arg0.toString(), BaseResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								Toast.makeText(context, "更改头像成功！",
										Toast.LENGTH_LONG).show();
								LoginUser user=UserCache.getOauth(ChildEditActivity.this);
								user.getChildlist().get(user.childPosition).setPath(result.getPath());
								UserCache.saveOAuth(user, ChildEditActivity.this);
								
								ImageLoader.getInstance().displayImage(result.getPath(), logo, options);
							} else {
								Toast.makeText(context, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
			}else{
				disMiss();
			}
		}
		
	}
	
	
	
	private void sendPacket(){
		
		if(BluetoothValue.INSTANCE.getConnectStatus()==BluetoothConstants.STATUS_CONNECTED){
			
			BluetoothPacket packet=new BluetoothPacket();
			int type=1;//mother

			String deviceString = deviceCode.getText().toString();
			int deviceType=BluetoothUtil.getDeviceType(deviceString);//当前注册的类型
			
			List<Byte> lists=new ArrayList<Byte>();
			for(Child child:UserCache.getOauth(this).getChildlist()){
				String deviceNo=child.getDeviceNo();
				if(BluetoothUtil.getDeviceType(deviceNo)==deviceType){
					String[] parts=deviceNo.split(":");
					if(parts.length==2){
						int part1=Integer.valueOf(parts[0],16);
						int part2=Integer.valueOf(parts[1],16);
						lists.add((byte)part1);
						lists.add((byte)part2);
					}
				}
			}
			
			if(lists.size()>0){
				int lenth=lists.size()/2;
				int size=lists.size()+4;
				byte[] con=new byte[size];
				
				//根据设备类型设置是绑定儿童还是婴儿
				if(deviceType==1){
					con[0]=(byte) 0xE7;
				}else if(deviceType==2){
					con[0]=(byte) 0xE6;
				}
				
				con[1]=(byte) lenth;
				con[2]=(byte) 0;
				con[3]=(byte) 0x0A;
				for(int i=4;i<size;i++){
					con[i]=lists.get(i-4);
				}
				packet.setData(con);
				
				if (BluetoothValue.INSTANCE.id != null) {
					packet.setId(BluetoothValue.INSTANCE.id);
				} else {
					return;
				}
				BluetoothUtil.packetData(packet, type);
				BluetoothSpp.getInstance().sendPacket(packet);
			}else{
				return;
			}
			
			
		}
		
	}
	
	

}
